<?php
// +----------------------------------------------------------------------
// | [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Author < 931274989@qq.com >
// +----------------------------------------------------------------------
// | Explain 用户地址接口
// +----------------------------------------------------------------------
namespace app\api\controller\v1;

use app\validate\api\AddressNew;
use app\api\service\Token as TokenService;
use app\lib\exception\UserException;
use app\lib\exception\SuccessMessage;
use app\api\controller\BaseController;
use app\model\User as UserModel;
use app\model\UserAddress;

class Address extends BaseController
{
  protected $beforeActionList = [
    'checkPrimaryScope' => ['only' => 'createOrUpdateAddress,getUserAddress']
  ];

  /**
   * 用户地址接口
   * 更新或新增用户地址
   * @url /Address
   * @http POST
   * @
   * 
   */
  public function createOrUpdateAddress()
  {
    $validate = new AddressNew();
    $validate->goCheck();
    // 根据Token获取uid
    // 根据uid来查看用户数据，判断用户是否存在，不存在抛出异常
    // 获取用户从客户端提交的地址信息
    // 根据用户地址信息是否存在，从而判断是更新还是新增
    $uid = TokenService::getCurrentUid();
    $user = UserModel::get($uid);
    if (!$user) {
      throw new UserException();
    }
    $dataArray = $validate->getDataByRule(input('post.'));
    $userAddress = $user->address;
    if (!$userAddress) {
      $user->address()->save($dataArray);
    }
    else {
      $user->address->save($dataArray);
    }
    return json(new SuccessMessage(),201);
  }

  /**
   * 获取用户地址接口
   * 获取数据库用户地址
   * @url /Address
   * @http GET
   * @
   * 
   */
  public function getUserAddress() {
    $uid = TokenService::getCurrentUid();
    $userAddress = UserAddress::where('user_id','=',$uid)->find();
    if (!$userAddress) {
      throw new UserException([
        'msg' => '用户地址不存在',
        'errorCode' => 60001
      ]);
    }
    return $userAddress;
  }
}
?>